package com.xncoding.jwt.controller;

import com.xncoding.jwt.config.swagger.SwaggerTagConst;
import io.swagger.annotations.Api;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;

/**
 * @author Dibbing Pan
 * @date 2019/8/27
 */
@Api(tags =  SwaggerTagConst.SSE.test_send, value = "test_send222", description = "服务端主动推送ces")
@Controller
@RequestMapping("/index")
public class IndexController {

    @GetMapping(path = "/envent/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public String test(@PathVariable String id) {
        return "连接成功";
    }

    @GetMapping
    @ResponseBody
    public Object yes() {
        return "success";
    }

    @GetMapping("/index")
    public Model index(Model model) {
        model.addAttribute("index.html");
        return model;
    }
    @GetMapping("/index2")
    public String index2(Model model) {
        model.addAttribute("index.html");
        return "index.html";
    }

    /**
     * "text/event-stream; charset=UTF-8"表明支持SSE这一服务器端推送技术，
     * 字段后面部分"charset=UTF-8"必不可少，否则无法支持SSE。
     * 服务器端发送的数据是连续的Stream，而不是一个数据包，
     * 因此浏览器接收到数据后，不会关闭连接。
     *
     * @return 服务端向浏览器推送的消息，具有一定的格式要求，详见SSE说明
     */
    @RequestMapping(value = "/push/{id}", produces = "text/event-stream; charset=UTF-8")
    @ResponseBody
    public String push(@PathVariable String id, HttpServletResponse response) {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        Random random = new Random();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        return "data:This is a test data " + random.nextInt() + " to " + id + "\n\n"; // SSE 要求的数据格式，详见SSE说明
    }


    @RequestMapping(value = "/push2/{id}", produces = "text/event-stream; charset=UTF-8")
    @ResponseBody
    public void push2(@PathVariable String id, HttpServletResponse response) {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        try {
            String value = "data: 中文测试" + id;
            Random random = new Random();
            while (!response.getWriter().checkError()){
                String message = value + random.nextInt();
                System.out.println(message);
                PrintWriter writer = response.getWriter();
                writer.write(message + " \n\n");//这里需要\n\n，必须要，不然前台接收不到值,键必须为data
                writer.flush();
                Thread.sleep(5 * 60 * 1000);
            }
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连续推送
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getDate", produces="text/event-stream;charset=UTF-8")
    @ResponseBody
    public void getDate(HttpServletResponse response) throws Exception {
        System.out.println("getDate event start");
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        while (!response.getWriter().checkError()) {
            response.getWriter().write("data:" + new Date() + "\n\n");
            response.getWriter().flush();
            Thread.sleep(10* 60 * 1000);
        }
        response.getWriter().close();
        System.out.println("getDate event end");
    }
}